package com.rk.admin.aop;
import com.rk.admin.domain.Logs;
import com.rk.admin.domain.User;
import com.rk.admin.service.LogsService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

@Aspect
@Component
public class SystemLogAspect {
    @Autowired
    private LogsService logsService;
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    //Controller层切点
    @Pointcut("@annotation(SystemControllerLog)")
    public void controllerAspect(){
    }


    @After("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        User user=null;
        try {
            user =(User) SecurityUtils.getSubject().getSession().getAttribute("user");
        } catch (InvalidSessionException e) {
        }

        //获得当前用户登录信息
        try {
            Logs logs = new Logs();

            String username = request.getHeader("username");
            //获取登录的用户

            //如果session中没有用户
            if(user!=null)
            {
                logs.setOpername(user.getUsername());//如果没有获取到session的用户 就用请求头中携带的
            }else {
                //如果session中没有用户
                if(username==null||username.equals(""))//访问主页 携带的username为空
                {
                    logs.setOpername("匿名用户");
                } else {
                    logs.setOpername(username);
                }
            }


            //操作方法
            logs.setMethods((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
            //操作描述
            logs.setDdesc(getControllerMethodDescription(joinPoint));
            //操作ip
            logs.setIp(request.getRemoteAddr());//获得访问IP地址记录到日志的IP属性中
            //操作时间
            logs.setOpertime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            if ( logsService.save(logs)){
                System.out.println("添加日志成功");
            }else{
                System.out.println("添加日志失败");
            }
        }catch (Exception e){
            //记录本地异常日志
            logger.error("==前置通知异常==");
            logger.error("异常信息：{}",e.getMessage());
        }
    }


    /**
     * @Description  获取注解中对方法的描述信息 用于Controller层注解
     * @date 2020年11月9日 上午12:01
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}
